/**
 * 订单核心数据概览
 * @author hanzhichen (hanzhichen@baijia.com)
 * @date 2021-03-02
 */

import {useState, useCallback, useEffect} from 'react';
import {useRequest} from 'ahooks';
import {Card} from 'antd';
import {querySelectOptions, queryValues} from '~/service/refundReport';
import SearchForm from '../../common/CommonSearchBar';
import {
    convertSearcherParams,
    formatRangePickerValue,
    addDashBoardIdToDimensionAndValues
} from '../../common/utils';
import OrderOfflineTableCard from './OrderOfflineTableCard';
import {searchFormCfg, dashBoardsCfg, selectUnitId} from './config';

// 设置默认时间
const current = new Date();
const initValues = {
    // eslint-disable-next-line no-magic-numbers
    // originPaidDay: [moment(current).subtract(30, 'days'), moment(current)]
};
const initPageInfo = {
    pageNum: 1,
    pageSize: 10
};
const formItemLayout = {
    labelCol: {span: 6},
    wrapperCol: {span: 18}
};
const tailLayout = {
    wrapperCol: {span: 24}
};

const formatDateSearchValueToDate = formatRangePickerValue('YYYYMMDD');
const formatDateSearchValueToTime = formatRangePickerValue('YYYY-MM-DD HH:mm');

// 将searchForm返回的值转化为后端需要的格式
const convertParams = params => {
    // 转换参数
    const {originPaidDay, ...rest} = params || {};
    let newSearcherParams = params;
    if (originPaidDay == null) {
        newSearcherParams = rest;
    } else {
        const formattedPayDate = formatDateSearchValueToDate(originPaidDay);
        const formattedPayTime = formatDateSearchValueToTime(originPaidDay);
        newSearcherParams = {
            dt: formattedPayDate,
            // eslint-disable-next-line babel/camelcase
            paid_time: formattedPayTime,
            ...rest
        };
    }
    const queryParams = convertSearcherParams(newSearcherParams);
    return queryParams;
};

const OrderOfflineTable = props => {
    const [loading, setLoading] = useState(false);
    // searchform
    // searchform中的select, 数据源全部都是动态从后端查询的
    const [selectOptions, setSelectOptions] = useState({});

    // 缓存查询参数中的表单部分
    const [dimensionAndValues, setDimensionAndValues] = useState(
        convertParams(initValues)
    );

    // chart查询方法
    const {data: data1, loading: loading1, run: run1} = useRequest(
        queryValues,
        {
            manual: true,
            formatResult(res) {
                return {data: res?.data, pager: res?.pager};
            }
        }
    );

    const [tableData, setTableData] = useState();
    const [pageInfo, setPageInfo] = useState(initPageInfo);

    useEffect(() => {
        setTableData(data1);
    }, [data1]);

    useEffect(() => {
        setLoading(loading1);
    }, [loading1]);

    /** 点击搜索按钮 */
    const handleSearch = useCallback(params => {
        const queryParams = convertParams(params);
        setDimensionAndValues(queryParams);
        const params1 = {
            dashBoardList: [dashBoardsCfg[0]],
            // dimensionAndValues,
            dimensionAndValues: addDashBoardIdToDimensionAndValues(
                queryParams,
                dashBoardsCfg[0].dashBoardId
            ),
            pager: pageInfo
        };
        run1(params1);
    }, []);

    /** 点击重置按钮 */
    const handleReset = useCallback(() => {
        const queryParams = convertParams(initValues);
        setDimensionAndValues(queryParams);
        setTableData();
        setPageInfo(initPageInfo);
    }, []);

    // 请求单个表单配置项
    const handleFetchOptions = useCallback(
        ({
            key,
            searchKey,
            pager,
            dependItemKey,
            dependItemValue,
            isGetingMore,
            options: curOptions,
            fieldsValue
        }) => {
            let permissions = [];
            searchFormCfg.forEach(item => {
                if (item.key === 'originPaidDay') {
                    // const originPaidDay = fieldsValue[item.key];
                    // if (originPaidDay) {
                    //     const formattedPayDate = formatDateSearchValueToDate(
                    //         originPaidDay
                    //     );
                    //     const formattedPayTime = formatDateSearchValueToTime(
                    //         originPaidDay
                    //     );
                    //     permissions.push({
                    //         dimensionId: `${selectUnitId}_dt`,
                    //         dimensionName: 'dt',
                    //         filterItems: formattedPayDate
                    //     });
                    //     permissions.push({
                    //         dimensionId: `${selectUnitId}_paid_time`,
                    //         dimensionName: 'paid_time',
                    //         filterItems: formattedPayTime
                    //     });
                    // }
                } else {
                    permissions.push({
                        dimensionId: `${selectUnitId}_${item.key}`,
                        dimensionName: item.key,
                        filterItems: Array.isArray(fieldsValue[item.key])
                            ? fieldsValue[item.key]
                            : fieldsValue[item.key] == null
                                ? []
                                : [fieldsValue[item.key]]
                    });
                }
            });

            permissions = permissions.filter(item => item.filterItems?.length);

            const params = {
                pager,
                dimensionId: `${selectUnitId}_${key}`,
                dimensionName: key,
                searchKey,
                permissions,
                unitId: selectUnitId
            };

            querySelectOptions(params).then(res => {
                const {data, pager} = res;
                let options =
                    data.map(item => ({
                        key: item,
                        value: item,
                        label: item
                    })) || [];
                // 分页时，累加展示
                if (isGetingMore) {
                    options = curOptions.concat(options);
                }
                setSelectOptions({key, options, pager});
            });
        },
        []
    );

    const handleTableChange = (pagination, filters, sorter, {action}) => {
        if (action === 'sort') {
            // 前端排序
            return;
        }
        const newPageInfo = {
            ...pageInfo,
            pageNum: pagination?.current ?? 1,
            pageSize: pagination?.pageSize ?? 10
        };
        setPageInfo(newPageInfo);
        const params1 = {
            dashBoardList: [dashBoardsCfg[0]],
            // dimensionAndValues,
            dimensionAndValues: addDashBoardIdToDimensionAndValues(
                dimensionAndValues,
                dashBoardsCfg[0].dashBoardId
            ),
            pager: newPageInfo
        };
        run1(params1);
    };

    return (
        <Card title="订单离线数据" className="special-class-order-offline">
            <SearchForm
                noCache
                formItemLayout={formItemLayout}
                tailLayout={tailLayout}
                labelAlign="left"
                config={searchFormCfg}
                selectOptions={selectOptions}
                initialValues={initValues}
                onOk={handleSearch}
                onReset={handleReset}
                onfetchOptions={handleFetchOptions}
                loading={loading}
            />
            <OrderOfflineTableCard
                dashBoard={dashBoardsCfg[0]}
                dimensionAndValues={dimensionAndValues}
                unitId={dashBoardsCfg[0].unitId}
                pageInfo={pageInfo}
                tableData={tableData}
                loading={loading1}
                onTableChange={handleTableChange}
            />
        </Card>
    );
};

export default OrderOfflineTable;
